package P2分治回溯;

public class NQueue {
    private static int count = 0;
    private static int N = 10;
    private static int[][] arr = new int[N][N];

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        nQueue(0);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        count = 0;

        Thread.sleep(5000);

        upper();
    }

    //0 1 2 3 4
    private static void upper() {
        long start = System.currentTimeMillis();
        int mid = (N % 2 == 0) ? N / 2 : N / 2 + 1;
        for (int col = 0; col < mid; col++) {
            arr[0][col] = 1;
            nQueueUpper(1);
            arr[0][col] = 0;
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    private static void nQueueUpper(int row) {
        if (row == N) {
            count++;
            System.out.println("The No." + count + " resolve");
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println();
            }
            count++;
            System.out.println("The No." + count + " resolve");
            for (int i = 0; i < N; i++) {
                for (int j = N - 1; j >= 0; j--) {
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println();
            }
        } else {
            for (int col = 0; col < N; col++) {
                if (check(row, col)) {
                    arr[row][col] = 1;
                    nQueueUpper(row + 1);
                    arr[row][col] = 0;
                }
            }
        }
    }

    private static void nQueue(int row) {
        if (row == N) {
            count++;
            System.out.println("The No." + count + " resolve");
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println();
            }
        } else {
            for (int col = 0; col < N; col++) {
                if (check(row, col)) {
                    arr[row][col] = 1;
                    nQueue(row + 1);
                    arr[row][col] = 0;
                }
            }
        }
    }

    private static boolean check(int row, int col) {
        //正上方
        for (int r = row - 1; r >= 0; r--) {
            if (arr[r][col] == 1) {
                return false;
            }
        }
        //左上方
        for (int r = row - 1, c = col - 1; r >= 0 && c >= 0; r--, c--) {
            if (arr[r][c] == 1) {
                return false;
            }
        }
        //右上方
        for (int r = row - 1, c = col + 1; r >= 0 && c < N; r--, c++) {
            if (arr[r][c] == 1) {
                return false;
            }
        }
        return true;
    }
}